package com.zzq.demo.tio.client.rest;

import com.zzq.demo.tio.client.HelloClient;
import com.zzq.demo.tio.common.HelloPacket;
import com.zzq.demo.tio.common.Type;
import com.zzq.demo.tio.common.packet.HelloMsgReqBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.Tio;
import org.tio.core.starter.TioServerBootstrap;
import org.tio.utils.json.Json;

import javax.annotation.Resource;

/**
 * @author zzq
 */
@RestController
public class HelloController {

    static Logger logger = LoggerFactory.getLogger(HelloController.class);

    @GetMapping("/")
    public String index() {
        return "Hello, tio-spring-boot-starter !!!";
    }

    /**
     * 推送消息到客户端
     *
     * @throws Exception
     */
    @GetMapping("/push")
    public String pushMessage() throws Exception {
        HelloMsgReqBody helloMsgReqBody = new HelloMsgReqBody();
        helloMsgReqBody.setText("好好学习，天天向上");
        HelloPacket packet = new HelloPacket();
        packet.setType(Type.SIMPLE_REQ);
        packet.setBody(Json.toJson(helloMsgReqBody).getBytes(HelloPacket.CHARSET));
        Tio.send(HelloClient.clientChannelContext, packet);
        logger.info("Push a message to client successfully");
        return "Push a message to client successfully";
    }
}
